package com.qst.rongxiaoserver.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

// JWT工具类  生成token  验证token
@Component
public class JwtUtil {
    @Value("${jwt.secret:defaultSecret}")
    private String secret;

    @Value("${jwt.expire}") // 默认2小时
    private Long expire;

    @Value("${jwt.issuer:defaultIssuer}")
    private String issuer;

//    生成JWT token
    public String generateToken(String userName) {
        return  JWT.create()
                .withIssuer(issuer)
                .withSubject(userName)
               .withExpiresAt(new Date(System.currentTimeMillis() + expire * 1000))
               .sign(Algorithm.HMAC256(secret));
    }

//    验证JWT token
    public String verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(secret))
                .withIssuer(issuer)
                .build()
                .verify(token)
                .getSubject();
    }

    // 检查token是否过期
    public boolean isTokenExpired(String token) {
        return JWT.require(Algorithm.HMAC256(secret))
                .withIssuer(issuer)
                .build()
                .verify(token)
                .getExpiresAt().before(new Date());
    }

}
